//机构设置  账户管理
<template>
  <a-card :bordered="false" :bodyStyle="{ padding: '24px 16px', height: '100%' }">
    <a-spin :spinning="confirmLoading">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="员工搜索">
                <a-input
                  v-model="keywords"
                  placeholder="请输入员工姓名/手机号码"
                  @pressEnter="$refs.table.refresh(true)"
                >
                  <a-tooltip slot="suffix" title="请输入员工姓名/手机号码">
                    <a-icon
                      type="search"
                      style="color: rgba(0,0,0,.45)"
                      @click="$refs.table.refresh(true)"
                    />
                  </a-tooltip>
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="是否在职">
                <a-checkbox :checked="queryParam.is_on_job==1" @change="onJob">在职</a-checkbox>
                <a-checkbox :checked="queryParam.is_on_job==2" @change="leaveJob">离职</a-checkbox>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row>
            <a-button
              type="primary"
              style="margin-bottom:20px;font-size:14px;"
              @click="visible = true"
            >新增账户</a-button>
          </a-row>
        </a-form>
        <!-- <a-alert type="warning" :message="description" banner class="user_management_warning" /> -->
      </div>
      <user-info-model
        ref="editUser"
        @reload="$refs.table.refresh()"
        @closeLoading="confirmLoading=false"
      ></user-info-model>
      <s-table
        :columns="columns"
        :data="loadData"
        ref="table"
        :showPagination="true"
        class="user_management_table"
        rowKey="id"
        :pagination="pagination"
        :scroll="{ x: 1500}"
      >
        <span slot="actions" slot-scope="text, record">
          <a-tag v-for="(action, index) in record.actionList" :key="index">{{ action.describe }}</a-tag>
        </span>
        <span slot="name" slot-scope="text,record">
          {{record.name}}
          <span v-if="record.is_top_admin==1" style="margin-left:10px;">
            <a title="主用户">
              <a-icon :component="inportantUser" style="font-size:16px;color:#ccc"></a-icon>
            </a>
          </span>
        </span>
        <span slot="status" slot-scope="text">{{ text | statusFilter }}</span>
        <span slot="job" slot-scope="text,record">
          <a-switch
            v-model="record.is_on_job"
            @change="changeJobType(record,$event)"
            :disabled="record.is_top_admin==1"
          />
        </span>
        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="handleDel(record)" :disabled="record.is_top_admin==1">删除</a>
        </span>
      </s-table>
      <a-modal
        title="新增账户"
        :width="640"
        :visible="visible"
        :confirmLoading="confirmLoading"
        @ok="handleSubmit('addFrom')"
        @cancel="visible = false"
        :destroyOnClose="true"
        :keyboard="false"
      >
        <a-spin :spinning="confirmLoading">
          <a-form-model :model="form" :rules="addRule" ref="addFrom">
            <a-form-model-item label="姓名" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input v-model="form.name" placeholder="请输入姓名" />
            </a-form-model-item>
            <a-form-model-item label="性别" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-radio-group v-model="form.sex">
                <a-radio :value="1">男</a-radio>
                <a-radio :value="2">女</a-radio>
              </a-radio-group>
            </a-form-model-item>
            <a-form-model-item
              label="手机号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="phone"
            >
              <a-input v-model="form.phone" placeholder="请输入手机号码" />
              <div class="noticeDiv">此手机号将作为用户登录本平台的账号</div>
            </a-form-model-item>
            <a-form-model-item
              label="密码"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="password"
            >
              <a-input type="password" v-model="form.password" placeholder="请输入密码" />
            </a-form-model-item>
            <a-form-model-item
              label="所属角色"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="role_ids"
            >
              <a-select v-model="form.role_ids" placeholder="请选择所属角色" allowClear mode="multiple">
                <a-select-option
                  v-for="(item,index) in rolesList"
                  :key="index"
                  :value="item.id"
                >{{item.name}}</a-select-option>
              </a-select>
              <div class="noticeDiv">选择角色后，该用户将获得对应的权限。</div>
            </a-form-model-item>
            <a-form-model-item label="所在部门" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select
                v-model="form.structures_ids"
                placeholder="请选择所在部门"
                allowClear
                mode="multiple"
              >
                <a-select-option
                  v-for="(item,index) in frameWorkList"
                  :key="index"
                  :value="item.id"
                >{{item.name}}</a-select-option>
              </a-select>
            </a-form-model-item>

            <a-form-model-item label="是否授课" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-switch v-model="form.is_teaching" />
              <div class="noticeDiv">如果员工需要授课，请开启授课状态</div>
            </a-form-model-item>
            <a-form-model-item
              label="擅长科目"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              v-if="form.is_teaching"
            >
              <a-select
                style="width:280px;"
                v-model="form.subject_ids"
                mode="multiple"
                placeholder="请选择擅长科目"
                @change="$forceUpdate()"
              >
                <a-select-option
                  v-for="(item,index) in subjectList"
                  :key="index"
                  :value="item.id"
                  v-if="item.is_enable==1"
                >{{item.name}}</a-select-option>
              </a-select>
              <span style="color:blue;cursor:pointer;float:right;" @click="showChild">科目管理</span>
            </a-form-model-item>
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="form.remark" placeholder="请输入(选填,最多输入255个字符)" :max-length="255" />
            </a-form-model-item>
          </a-form-model>
        </a-spin>
      </a-modal>
      <subject-model ref="subj_model" @reload="reloadSelect" />
    </a-spin>
  </a-card>
</template>

<script>
import { STable } from '@/components'
import {
  accountList,
  accountCreate,
  accountDel,
  accountEdit,
  accountSureDel,
  roleList,
  moveAndDel,
  changeOnJobType,
} from '@/api/account'
import { changeUserInfo } from '@/api/login'
import { inportantUser } from '@/core/icons'
import { subjectList } from '@/api/subject'
import { campusList } from '@/api/structure'
import userInfoModel from '@/components/editUserInfo'
import subjectModel from '@/components/subjectsModel'
import store from '@/store'
export default {
  name: 'TableList',
  components: {
    STable,
    subjectModel,
    userInfoModel,
  },
  data() {
    return {
      pagination:{
        showTotal:total=>`共${total}条数据`,
      },
      inportantUser,
      description:
        '列表使用场景：后台管理中的权限管理以及角色管理，可用于基于 RBAC 设计的角色权限控制，颗粒度细到每一个操作类型。',

      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
      },
      mdl: {},
      layout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 14 },
      },
      visible: false, //新增弹窗
      visibles: false, //编辑弹窗
      confirmLoading: false, //遮罩层确定按钮loading
      form: {
        name: undefined,
        phone: undefined,
        password: undefined,
        structures_ids: [],
        role_ids: [],
        remark: undefined,
        is_teaching: true,
        sex: 1,
      },
      subjectList: [],
      addRule: {
        name: [{ required: true, message: '请输入姓名！' }],
        phone: [{ required: true, pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码！' }],
        password: [
          {
            required: true,
            pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/,
            message: '请输入6-16位字母和数字组合(禁用标点符号)的密码！',
          },
        ],
        role_ids: [{ required: true, message: '请选择所属角色' }],
      },
      ruleForm: {
        name: '',
        phone: '',
        remark: '',
      },
      rules: {
        name: [{ required: true, message: '请输入姓名！' }],
        role_ids: [{ required: true, message: '请选择所属角色' }],
      },
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      keywords: '',
      queryParam: {
        school_id: this.$store.state.user.school,
        is_on_job: null,
      },
      // 表头
      columns: [
        {
          title: '姓名',
          dataIndex: 'name',
          width: 200,
          fixed:'left',
          scopedSlots: {
            customRender: 'name',
          },
        },
        {
          title: '手机号码',
          dataIndex: 'phone',
        },
        {
          title: '是否授课',
          dataIndex: 'is_teaching',
          align: 'center',
          customRender: (text) => {
            return text == true ? '是' : '否'
          },
        },
        {
          title: '备注',
          width: 300,
          ellipsis: true,
          dataIndex: 'remark',
        },
        {
          title: '角色',
          dataIndex: 'role',
          width: 200,
          ellipsis: true,
          customRender: (text, record) => {
            if (record.role && record.role.info && record.role.info.length > 0) {
              let arr = []
              record.role.info.forEach((val) => {
                arr.push(val.name)
              })
              let data = arr.join('，')
              return data
            } else {
              return '-'
            }
          },
        },
        {
          title: '在职状态',
          dataIndex: 'isOnJob',
          scopedSlots: { customRender: 'job' },
        },
        {
          title: '操作',
          width: '150px',
          dataIndex: 'action',
          fixed:'right',
          scopedSlots: { customRender: 'action' },
        },
      ],
      // 向后端拉取可以用的操作列表
      permissionList: null,
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        return accountList(Object.assign(parameter, this.queryParam, { keywords: this.keywords }))
          .then((res) => {
            const result = res
            return result
          })
          .catch((err) => {
            this.$message.error(err.data.message || '获取数据失败，请刷新页面或稍后再试')
          })
      },
      frameWorkList: [],
      rolesList: [],
      selectedRowKeys: [],
      selectedRows: [],
    }
  },
  created() {
    campusList({
      school_id: this.$store.state.user.school,
      type: 2,
    }).then((res) => {
      this.frameWorkList = res
    })
    roleList({
      school_id: this.$store.state.user.school,
      pageSize: 99999999999,
    }).then((res) => {
      this.rolesList = res.data
    })
    subjectList({
      pageSize: 999999,
      school_id: this.$store.state.user.school,
    })
      .then((res) => {
        this.subjectList = res.data
      })
      .catch((error) => {
        this.$message.error(err.data.message || '获取授课科目失败')
      })
    // this.callport()
  },
  methods: {
    con() {
      console.log(this.$store.state.user)
    },
    handleSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.confirmLoading = true
          let values = JSON.parse(JSON.stringify(this.form))
          if (values.is_teaching !== true) {
            values.is_teaching = false
          }
          if (values.remark) {
          } else {
            values.remark = ''
          }
          values.school_id = this.$store.state.user.school
          accountCreate(values)
            .then((res) => {
              this.$message.success('添加成功')
              this.visible = false
              this.$refs.table.refresh(true)
              this.confirmLoading = false
            })
            .catch((err) => {
              this.confirmLoading = false
              this.$message.error(err.data.message || '添加失败')
            })
        } else {
          return false
        }
      })
    },
    handleEdit(record) {
      let data = JSON.parse(JSON.stringify(record))
      data.subject_ids = record.subject_id
      data.sex = record.sex ? record.sex : 1
      data.role_ids = record.roleID
      data.structures_ids = record.department_ids
      this.confirmLoading = true
      this.$refs.editUser.showVisible(data)
    },
    //移出并离职
    moveDel(id) {
      moveAndDel({
        user_id: id,
        school_id: this.$store.state.user.school,
        is_on_job: false,
      })
        .then((res) => {
          this.$message.success('离职成功')
          this.$refs.table.refresh()
        })
        .catch((err) => {
          this.$message.error(err.data.message || '离职失败')
          return
        })
    },
    // sureDel(id, type) {
    //   accountSureDel({
    //     user_id: id,
    //     school_id: this.$store.state.user.school,
    //     is_on_job: type == 2 ? false : true
    //   })
    //     .then(res => {
    //       this.$message.success('离职成功')
    //       this.$refs.table.refresh()
    //     })
    //     .catch(err => {
    //       this.$message.error(err.data.message || '离职失败')
    //       return
    //     })
    // },
    handleDel(e) {
      let that = this
      this.$confirm({
        title: '确认要删除这个员工吗？',
        content: '删除后，员工将不能登录系统，此操作不能被撤销',
        okText: '确认',
        okType: 'primary',
        cancelText: '取消',
        onOk() {
          accountDel({ school_id: that.$store.state.user.school, user_id: e.id })
            .then((res) => {
              if (res.message !== '' && res.stateCheck == true) {
                that.$confirm({
                  title: '提示',
                  content: res.message,
                  okText: '移除并离职',
                  okType: 'primary',
                  cancelText: '取消',
                  onOk() {
                    that.moveDel(e.id)
                  },
                  onCancel() {},
                })
              } else if (res.message == '' && res.stateCheck == true) {
                //直接删除
                that.moveDel(e.id)
              } else {
                //不能删除
                that.$message.warning(res.message)
              }
            })
            .catch((err) => {
              that.$message.error(err.data.message || '删除失败~')
            })
        },
        onCancel() {},
      })
    },
    changeJobType(data, e) {
      let that = this
      if (e == false) {
        if (that.$store.state.user.id == data.id) {
          this.$confirm({
            title: '确定要将您自己标记为离职吗？',
            content: '标记离职后，您将返回登录界面，并不能登录本学校',
            okText: '确认',
            okType: 'primary',
            cancelText: '取消',
            onOk() {
              changeOnJobType({ school_id: that.$store.state.user.school, user_id: data.id, is_on_job: e })
                .then((res) => {
                  store.dispatch('Logout')
                })
                .catch((err) => {
                  that.$refs.table.refresh()
                  that.$message.error(err.data.message || '切换状态失败')
                })
            },
            onCancel() {
              that.$refs.table.refresh()
            },
          })
        } else {
          this.$confirm({
            title: '确定要将员工标记为离职吗？',
            content: '标记离职后，员工将不能登录系统',
            okText: '确认',
            okType: 'primary',
            cancelText: '取消',
            onOk() {
              changeOnJobType({ school_id: that.$store.state.user.school, user_id: data.id, is_on_job: e })
                .then((res) => {
                  that.$refs.table.refresh()
                })
                .catch((err) => {
                  that.$refs.table.refresh()
                  that.$message.error(err.data.message || '切换状态失败')
                })
            },
            onCancel() {
              that.$refs.table.refresh()
            },
          })
        }
      } else {
        changeOnJobType({ school_id: that.$store.state.user.school, user_id: data.id, is_on_job: e })
          .then((res) => {
            that.$refs.table.refresh()
          })
          .catch((err) => {
            that.$refs.table.refresh()
            that.$message.error(err.data.message || '切换状态失败')
          })
      }
    },
    onJob(e) {
      if (e.target.checked == true) {
        this.queryParam.is_on_job = 1
      } else {
        this.queryParam.is_on_job = null
      }
    },
    leaveJob(e) {
      if (e.target.checked == true) {
        this.queryParam.is_on_job = 2
      } else {
        this.queryParam.is_on_job = null
      }
    },
    showChild() {
      this.$refs.subj_model.showModal()
    },
    reloadSelect() {
      subjectList({
        pageSize: 999999,
        school_id: this.$store.state.user.school,
      })
        .then((res) => {
          this.subjectList = res.data
        })
        .catch((error) => {
          this.$message.error(err.data.message || '获取授课科目失败')
        })
    },
  },
  watch: {
    'queryParam.keywords'(val) {
      this.$refs.table.refresh()
    },
    'queryParam.is_on_job'(val) {
      this.$refs.table.refresh()
    },
    visible(val) {
      if (val == false) {
        this.form = {
          name: undefined,
          phone: undefined,
          password: undefined,
          structures_ids: [],
          role_ids: [],
          remark: undefined,
          is_teaching: true,
          sex: 1,
        }
      }
    },
  },
}
</script>
<style lang="less" scoped>
</style>
<style lang="less">
.user_management_warning {
  margin-bottom: 20px;
  background-color: #fff0e7;
}
.user_management_warning .ant-alert-message {
  color: rgba(0, 0, 0, 0.65);
}
</style>
